package com.haoyun.common.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.haoyun.common.constant.SecurityConstants;
import com.haoyun.common.controller.UserInfo;
import com.haoyun.common.core.BaseException;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * Created by twg on 2018/6/15.
 * 公共字段自动填充
 */
@Component
public class PublicFieldAutomaticFilling extends MetaObjectHandler {
    @Autowired
    private HttpServletRequest request;

    @Override
    public void insertFill(MetaObject metaObject) {
        insert(metaObject);
        update(metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        update(metaObject);
    }

    private void insert(MetaObject metaObject){
        Object creator = getFieldValByName("creator", metaObject);
        Object gmtCreate = getFieldValByName("gmtCreate", metaObject);
        //公司ID
        Object compId = getFieldValByName("compId", metaObject);
        if (null == compId){
            setFieldValByName("compId", currentUser().getCompId(), metaObject);
        }
        if (null == creator) {
            setFieldValByName("creator", currentUser().getId(), metaObject);
        }
        if (null == gmtCreate) {
            setFieldValByName("gmtCreate", new Date(), metaObject);
        }
    }

    private void update(MetaObject metaObject){
        Object modifier = getFieldValByName("modifier", metaObject);
        Object gmtModified = getFieldValByName("gmtModified", metaObject);
        if (null == modifier) {
            setFieldValByName("modifier", currentUser().getId(), metaObject);
        }
        if (null == gmtModified) {
            setFieldValByName("gmtModified", new Date(), metaObject);
        }
    }

    private UserInfo currentUser() {
        String userInfo = request.getHeader(SecurityConstants.USER_INFO_HEADER);
        if (StrUtil.isBlank(userInfo)) {
            throw new BaseException("请求头未设置用户信息！");
        }
        Map userMap = (Map) JSON.parse(userInfo);
        return BeanUtil.mapToBean(userMap, UserInfo.class, true);
    }
}
